/* 手写myInstanceof方法,实现myInstanceof(zhangsan,Person)返回一个布尔值，判断一个实例是否为某个构造函数的后代实例 */
// class Person {
//   constructor(name) {
//     this.name = name
//   }

//   eat(food) {
//     console.log(this, "eat", food);
//   }
// }

// class Student extends Person {
//   study() {
//     console.log(this, "study");
//   }
// }

// function myInstanceof(ins, targetClass) {
//   while (ins) {
//     console.log(ins);
//     if (ins.constructor === targetClass) {
//       return true
//     }
//     ins = ins.__proto__
//   }
//   return false
// }

/* 手写instanceof实现2：递归实现 */
function myInstanceof(ins, targetClass) {
  if (!ins) {
    return false;
  }

  if (ins.constructor === targetClass) {
    return true;
  }

  return myInstanceof(ins.__proto__, targetClass);
}

// console.log(myInstanceof(new Student("张三"), Person));//true
// console.log(myInstanceof({ name: "李四" }, Person));






/* 手写new操作符 */
/* 手写const p = myNew(Person,”张三”)，实现const p = new Person(”张三”)相同的效果 */
function Person(name) {
  this.name = name;
}

Person.prototype.eat = function (food) {
  console.log(this, "eat", food);
};

function myNew(construtor, name) {
  const obj = {};

  // 绑定this为obj
  Person.call(obj, name);

  // 将obj的妈指向构造函数的老婆
  obj.__proto__ = construtor.prototype;

  return obj;
}

// new Person("张三").eat("shit");
// myNew(Person, "张三").eat("shit");






/* 手写数组去重 */
// 实现数组去重，例如 noRepeat([3,1,4,1,5,3])输出[3,1,4,5]
function noRepeat(arr = []) {
  // return [...new Set(arr)]

  return arr.filter((item, i) => arr.indexOf(item) === i);
}

console.log(noRepeat([3, 1, 4, 1, 5, 3]));
